package org.example.itext;

import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.security.ExternalSignatureContainer;
import com.itextpdf.text.pdf.security.MakeSignature;
import org.example.jida.JiDaSigUtil;

import java.io.*;

public class PdfSignerWithJidaHSM {

    private static final String IN_DIR = "src/main/resources/signature/";
    private static final String OUT_DIR = "target/test-output/";
    private static final String KEYSTORE_PATH = IN_DIR + "keystore.p12";
    private static final String JPEG_PATH = IN_DIR + "stamp.jpg";
    private static final String PASSWORD = "123456";

    static {
        new File(OUT_DIR).mkdirs();
    }

    public static void main(String[] args) throws Exception {
        try {
            String yuanPdf= "D:\\todo.pdf";
            String signPdf= OUT_DIR + "sign_me_itx.pdf";

            // 加载PDF文档
            PdfReader reader = new PdfReader(yuanPdf);
            FileOutputStream os = new FileOutputStream(signPdf);
            PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');

            // 创建签名外观
            PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
            appearance.setReason("签名原因");
            appearance.setLocation("签名地点");
            appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "signature");

            // 设置外部签名容器
            ExternalSignatureContainer external = new JidaHSMExternalSignatureContainer();

            // 应用签名
            //SubMakeSignature.signExternalContainer(appearance, external, 8192);//使用修改源码方式进行签名
            MakeSignature.signExternalContainer(appearance, external, 8192);//使用原始方式签名

            // 关闭资源
            stamper.close();
            reader.close();
            os.close();
            System.out.println("签名完成！");
            //验证
            //JITUtil.itextVerifyEdit(signPdf);//使用修改源码方式进行验证
            JiDaSigUtil.itextVerifyOriginal(signPdf);//使用修改源码方式进行验证

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
